package cn.flyingroc.travelbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

import cn.flyingroc.travelbook.util.DatabaseHelper;
import cn.flyingroc.travelbook.util.Formatter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class NewPOI extends Activity {
	
	public static final String TAG = "newpoi";
	
	private Bitmap localBitmap = null;
	private ImageView mIvPhoto;
	private EditText desc_new_poi;
	private EditText title_new_poi;
	private ImageButton photo_bottom_new_poi;
	private ImageButton file_bottom_new_poi;
	private ImageButton mIbCancelPhoto;
	private CheckBox isGetPosition_bottom_new_poi;
	private Button commit_bottom_new_poi;
	private LocationManager locationmanager1;
	private LinearLayout position_new_poi;
	private LinearLayout dynamicphoto_new_poi;
	private TextView info_position_new_poi;
	private boolean gpsFlag = false;
	private double lat;
	private double lon;
	private String photoname = null;
	Context context;
	private ProgressDialog progressDialog = null;
	private DatabaseHelper databaseHelper;
	private SQLiteDatabase sqliteDatabase;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		// Hide the window title.
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
		
        setContentView(R.layout.newpoi);
    	
        //init DB
		context = getApplicationContext();
		this.open(context);
        
        position_new_poi = (LinearLayout)findViewById(R.id.position_new_poi);
        position_new_poi.setVisibility(LinearLayout.GONE);
        
        dynamicphoto_new_poi = (LinearLayout)findViewById(R.id.dynamicphoto_new_poi);
        dynamicphoto_new_poi.setVisibility(LinearLayout.GONE);
        
        title_new_poi = (EditText)findViewById(R.id.title_new_poi);
        desc_new_poi = (EditText)findViewById(R.id.desc_new_poi);
        info_position_new_poi = (TextView)findViewById(R.id.info_position_new_poi);
        
		photo_bottom_new_poi = (ImageButton)findViewById(R.id.photo_bottom_new_poi);
		photo_bottom_new_poi.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Log.i(TAG, "photo begins");
				initCamera();
			}
		});
		
		file_bottom_new_poi = (ImageButton)findViewById(R.id.file_bottom_new_poi);
		file_bottom_new_poi.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Log.i(TAG, "file begins");
				initFile();
			}
		});
		
		mIvPhoto = (ImageView)findViewById(R.id.imv_dynamicphoto_new_poi);
		
		isGetPosition_bottom_new_poi = (CheckBox)findViewById(R.id.isGetPosition_bottom_new_poi);
		isGetPosition_bottom_new_poi.setChecked(true);
		/*
		isGetPosition_bottom_new_poi.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener() {	
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					bootGPS();
				}else{
					stopGPS();
				}
			}
		});*/
		
		commit_bottom_new_poi = (Button)findViewById(R.id.commit_bottom_new_poi);
		commit_bottom_new_poi.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if (!gpsFlag){
					if(isGetPosition_bottom_new_poi.isChecked()){
						Main.mMakeTextToast(getApplicationContext(),"GPS还未完成定位，请等待...",true);
						return;
					}
				}
				
				//savePhotoFile();
				progressDialog = ProgressDialog.show(NewPOI.this, "请稍等...", "保存兴趣点...", true); 
				new Thread() {
		            public void run() {
		            	try{
							if (localBitmap!=null){
								writeToFile(localBitmap);
							}
							
							byte[] b = desc_new_poi.getText().toString().replaceAll("'", "''").getBytes();
							String desc = new String(b,"UTF-8");
							Log.i("desc===", desc);
							byte[] t = title_new_poi.getText().toString().replaceAll("'", "''").getBytes();
							String title = new String(t,"UTF-8");
							Log.i("title===", title);
							saveItem(title,desc);
							Intent i = new Intent(NewPOI.this, Main.class);
			                Bundle bundle = new Bundle();
			                bundle.putString("source", TAG);
			                i.putExtras(bundle);
			                startActivity(i);
			                finish();
						}catch(Exception ex){
							ex.printStackTrace();
						}
		                progressDialog.dismiss();
		            }
		            
		        }.start();
				
			}
			
		});
		
		mIbCancelPhoto = (ImageButton)findViewById(R.id.cancel_dynamicphoto_new_poi);
		mIbCancelPhoto.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				mIvPhoto.setImageBitmap(null);
				dynamicphoto_new_poi.setVisibility(LinearLayout.GONE);
				if(localBitmap.isRecycled()==false){
					localBitmap.recycle();
				}
				localBitmap = null;
			}
		});
		
		//初始化的时候检查，如果需要上传GPS位置，则启动GPS定时扫描服务
		locationmanager1 = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		bootGPS();
		
	}
	
	/** 
     * 打开数据库连接 
     */
    public void open(Context context)
    {
        databaseHelper = new DatabaseHelper(context);
        
        try
        {
            sqliteDatabase = databaseHelper.getWritableDatabase();
        }catch(SQLiteException ex)
        {
            sqliteDatabase = databaseHelper.getReadableDatabase();
        }
    }
    
    /** 
     * 关闭数据库连接 
     */  
    public void close()
    {  
        sqliteDatabase.close();  
    }
	
	public void saveItem(String title,String desc){
		Date date = new Date();
		String timestamp = Formatter.sdf.format(date);
		
		String sql = "insert into MYPOI(TITLE,DESC,LAT,LON,PHOTONAME,CREATETIME) values ('"+title+"','" + desc + "'," 
		+ lat  + "," + lon+ ",'" + photoname + "','"+timestamp+"')";
		Log.i("sql==", sql);
	    try {
	        this.sqliteDatabase.execSQL(sql);
	        this.close();
	        Log.i(TAG, "insert  Table TravelBook 1 record ok");
	    } catch (Exception e) {
	    	e.printStackTrace();
	        Log.i(TAG, "insert  Table TravelBook 1 record fail");
	    }
	}
	
	private void bootGPS(){
		locationmanager1.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 20, locationListener);
	}
	
	/*
	private void stopGPS(){
		locationmanager1.removeUpdates(locationListener);
		position_new_poi.setVisibility(LinearLayout.GONE);
	}
	*/
	
	private final LocationListener locationListener = new LocationListener() {
		
		//当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
		public void onLocationChanged(Location location) {
	        // log it when the location changes
	        if (location != null) {
	        	if(!gpsFlag){
	        		infoPosition(location);
	        	}
	        }
	    }
	    
		//Provider被disable时触发此函数，比如GPS被关闭
	    public void onProviderDisabled(String provider) {
	    	
	    }
	    
	    //Provider被enable时触发此函数，比如GPS被打开
	    public void onProviderEnabled(String provider) {
	    	
	    }
	    
	    //Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
	    public void onStatusChanged(String provider, int status, Bundle extras) {
	    	
	    }
	};
	
	
	private void infoPosition(Location location){
		Main.mMakeTextToast(this.context,"GPS已经完成定位",true);
		gpsFlag = true;
		lat = location.getLatitude();
		lon = location.getLongitude();
		position_new_poi.setVisibility(LinearLayout.VISIBLE);
		info_position_new_poi.setText("GPS已经定位："+
				"Latitude="+String.valueOf(location.getLatitude())+"\r\n" +
						"Longitude="+String.valueOf(location.getLongitude()));
	}
	
	private void initCamera(){
		int k = 0;
		Intent localIntent1 = new Intent("android.media.action.IMAGE_CAPTURE");
	    String str1 = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString();
	    localIntent1.putExtra("output", str1);
	    startActivityForResult(localIntent1, k);
	}
	
	private void initFile(){
		int j = 1;
		Uri localUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        Intent localIntent2 = new Intent("android.intent.action.PICK", localUri);
        startActivityForResult(localIntent2, j);
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("requestCode:", String.valueOf(requestCode));
		Log.i("resultCode:", String.valueOf(resultCode));
		
	    if (resultCode != -1)
	    	return;
	    	
	      switch (requestCode)
	      {
	      default:
	        break;
	      case 0:
	        localBitmap = (Bitmap)data.getExtras().get("data");
	        if (localBitmap == null)
	        {
	          Uri localUri1 = data.getData();
	          import_picture(localUri1);
	        }
	        this.mIvPhoto.setImageBitmap(localBitmap);
	        setViewZoneVisible(true);
	        break;
	      case 1:
	        
	        Log.i(TAG, data.getData().toString());
	        
	          //writeToFile(localBitmap);
	          Uri localUri2 = data.getData();
	          import_picture(localUri2);
	          Log.i(TAG, localBitmap==null?"null":"not null");
	          this.mIvPhoto.setImageBitmap(localBitmap);
	          setViewZoneVisible(true);
	          
	          break;
	      }
	      
	}
	
	private void setViewZoneVisible(boolean paramBoolean){
	    if (paramBoolean)
	      this.dynamicphoto_new_poi.setVisibility(LinearLayout.VISIBLE);
	}
	
	private void import_picture(Uri paramUri){
	    BitmapFactory.Options localOptions;
	    try{
	      localOptions = new BitmapFactory.Options();
	      //localOptions.inSampleSize = 4;
	      InputStream ins = getContentResolver().openInputStream(paramUri);
	      localBitmap = BitmapFactory.decodeStream(ins, null, localOptions);
	      ins.close();
	    }
	    catch (Exception localException){
	    	localException.printStackTrace();
	    }
	  }
	
	private void writeToFile(Bitmap paramBitmap) throws FileNotFoundException, IOException{
		photoname = getPhotoFileName();
	    FileOutputStream localFileOutputStream = new FileOutputStream(Main.PHOTO_PATH+photoname);
	    Bitmap.CompressFormat localCompressFormat = Bitmap.CompressFormat.JPEG;
	    paramBitmap.compress(localCompressFormat, 70, localFileOutputStream);
	    localFileOutputStream.close();
	}
	
	public String getPhotoFileName(){
		int year = Calendar.getInstance().get(Calendar.YEAR);
        
        int month = Calendar.getInstance().get(Calendar.MONTH);
        String strMonth="";
        if (month<10){
            strMonth = "0"+String.valueOf(month);
        }else{
            strMonth = String.valueOf(month);
        }
        
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        String strDay="";
        if (day<10){
            strDay = "0"+String.valueOf(day);
        }else{
            strDay = String.valueOf(day);
        }
        
        String filename = "IMAGE"+String.valueOf(year)+
        strMonth+
        strDay+
        String.valueOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY))+
        String.valueOf(Calendar.getInstance().get(Calendar.MINUTE))+
        String.valueOf(Calendar.getInstance().get(Calendar.SECOND))+
        String.valueOf(Calendar.getInstance().get(Calendar.MILLISECOND));
        return filename+".jpg";
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	public static void main(String args[]){
		String filename = ""+Calendar.YEAR+Calendar.MONTH+Calendar.DAY_OF_MONTH+Calendar.HOUR_OF_DAY+Calendar.MINUTE+Calendar.MILLISECOND;
		System.out.println(filename);
	}
	
}
